package com.kristin.proxy;

import com.kristin.proxy.cglib.CglibMethodInterceptor;
import com.kristin.proxy.staticProxy.ProxyAnimal;
import net.sf.cglib.core.DebuggingClassWriter;

import java.lang.reflect.Field;
import java.util.Properties;

/**
 * @ClassName ProxyTest
 * @Description TODO
 * @Author Kristin
 * @Date 2020/09/17 10:24:22
 * @Version 1.0.0
 */
public class ProxyTest {

    public static void main(String[] args)  throws Exception{
        // 静态代理测试
//        staticProxyTest();


        // JDK动态代理测试
//        jdkProxyTest();


        // cglib动态代理测试
        cglibSyncProxyTest();
    }

    static void staticProxyTest() {
        // 静态代理测试
        System.out.println("---------------------");
        Animal animal = new Dog();
        // 正常调用
        animal.call();
        // 执行代理
        System.out.println("---------------------");
        Animal proxyAnimal = new ProxyAnimal(animal);
        proxyAnimal.call();
        System.out.println("---------------------");
    }




    static void cglibSyncProxyTest() throws NoSuchFieldException, IllegalAccessException {
        saveLocal();
        // 针对类来实现代理的，针对目标类生成一个它的子类，并覆盖其中的业务方法来实现代理。
        // 因为采用继承,所以不能被继承的方法(被final修饰)不能被代理
        CglibMethodInterceptor interceptor = new CglibMethodInterceptor();
        Animal animal = (Animal)interceptor.CglibProxyGeneratory(Dog.class);
        animal.call();


    }

    public static void saveLocal() throws NoSuchFieldException, IllegalAccessException  {
        // 存储到本地
        Field field = System.class.getDeclaredField("props");
        field.setAccessible(true);
        Properties props = (Properties) field.get(null);
        System.setProperty(DebuggingClassWriter.DEBUG_LOCATION_PROPERTY, "D://class");//dir为保存文件路径
        props.put("net.sf.cglib.core.DebuggingClassWriter.traceEnabled", "true");
    }

}
